//仓库
import { reqGetCode, reqUserRegister, reqUserLogin, reqUserInfo, reqLoginOut } from '@/api'
import { setToken } from '@/utils/token'
//actions：处理actions，可以书写自己的业务逻辑，也可以处理异步
const actions = {
    async getCode({ commit }, phone) {
        let result = await reqGetCode(phone)
        if (result.code == 200) {
            commit('GETCODE', result.data);
        } else {
            return Promise.reject(new Error('faile'))
        }

    },
    //注册
    async getUserRegister({ commit }, user) {
        let result = await reqUserRegister(user)
        // console.log(result);
        if (result.code == 200) {
            return "ok";
        } else {
            return Promise.reject(new Error('falie'))
        }
    },
    //用户登录时发送的请求
    async getUserLogin({ commit }, data) {
        let result = await reqUserLogin(data)
        // console.log(result);
        if (result.code == 200) {
            commit('GETISERLOGIN', result.data.token)
            setToken(result.data.token)
        } else {
            return Promise.reject(new Error('falie'))
        }
    },

    //获取用户登录信息
    async getUserInfo({ commit }) {
        let result = await reqUserInfo();
        // console.log(result);
        if (result.code == 200) {
            commit('GETUSERINFO', result.data);
            return 'OK';
        } else {
            // return Promise.reject(new Error('faile'))
        }
    },

    //退出登录
    async getLoginOut({ commit }) {
        let result = await reqLoginOut();
        if (result.code = 200) {
            commit('GETLOGINOUT')
            return 'OK'
        } else {
            return Promise.reject(new Error('退出登录失败'))
        }
    }

};

//mutations：修改state的唯一手段
const mutations = {

    //注册时，获取验证码的mutations
    GETCODE(state, code) {
        state.code = code
    },
    GETISERLOGIN(state, token) {
        state.token = token
    },
    GETUSERINFO(state, userInfo) {
        state.userInfo = userInfo
    },
    //清除本地数据
    GETLOGINOUT(state) {
        state.token = ''
        state.userInfo = '',
            localStorage.removeItem("TOKEN");

    }
};

//state:仓库存储数据的地方
const state = {
    //注册时用的code
    code: '',
    //
    token: localStorage.getItem("TOKEN"),
    userInfo: ''
};

//getters：理解为计算属性，可以简化仓库数据，让组件获取仓库的数据更加方便
const getters = {};


export default {
    actions,
    mutations,
    state,
    getters
}
